package com.example.communist_app_api.controller.uniapp;

import com.example.communist_app_api.config.mq.NoticeTask;
import com.example.communist_app_api.db.dto.OrganizationDTO;
<<<<<<< HEAD
import com.example.communist_app_api.db.pojo.Organization;
import com.example.communist_app_api.db.pojo.Role;
import com.example.communist_app_api.db.pojo.User;
<<<<<<< HEAD
import com.example.communist_app_api.enums.SenderNameEnum;
=======
import com.example.communist_app_api.db.pojoDto.Organization;
import com.example.communist_app_api.db.pojoDto.Role;
import com.example.communist_app_api.db.pojoDto.User;
>>>>>>> 党建uniapp/dev
=======
>>>>>>> parent of aec1d46 (消息模块的搭建和配合其他模块消息的发送和收取)
import com.example.communist_app_api.enums.StatusEnum;
import com.example.communist_app_api.exception.GlobalException;
import com.example.communist_app_api.service.*;
import com.example.communist_app_api.util.*;
import com.example.communist_app_api.vo.uniapp.req.UniAppLoginReq;
import com.example.communist_app_api.vo.uniapp.req.UniAppPersonUpdateUserReq;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * @author love~mlm
 * @version 1.0
 * Create by 2023/2/17 16:07
 */
@RestController
@RequestMapping("/uniApp/user")
public class UniAppUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private UserOrganizationService userOrganizationService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private RedisUtil redisUtil;

    @Value("${communist.jwt.cache-expire}")
    private int cacheExpire;

    @Autowired
    NoticeTask noticeTask;

    public static final String pattern = "^[\\u4e00-\\u9fa5.·\\u36c3\\u4DAE]{2,10}$";

    @PostMapping("/uploadImage")
    @ApiOperation("上传头像")
    public R uploadImage(MultipartFile multipartFile) {
        if (multipartFile == null) {
            return R.error("上传失败");
        }
        String photoUrl = CosUtils.uploadFile(multipartFile, "");
        return R.ok("上传成功").put("imageUrl", photoUrl);
    }


    //登录
    @PostMapping("/login")
    @ApiOperation("登录用户")
    public R login(@Valid @RequestBody UniAppLoginReq req){
        //登录/注册环节
        int id = userService.login(req);
        // 生成jwt token
        String token= jwtUtils.genJwtToken(String.valueOf(id));
        User user = userService.getUserByUserId(id);
        //登录时接收通知
        noticeTask.receiveAsync(id+"");
        //通过ID获取
        //权限
        //Set<String> permsSet = userService.searchUserPermissions(id);
        saveCacheToken(token,id);
        String organizationName = userOrganizationService.selectOrganizationNameByUserId(id);
        List<Role> roleList = userRoleService.getRoleByUserId(id);
        //return R.ok("登录成功").put("token",token).put("permission",permsSet).put("userId",id);
        return R.ok("登录成功").put("token",token).put("user",user).put("organizationName",organizationName)
                .put("roleList",roleList);
    }

    //查询所有组织信息
    @PostMapping("/allOrganization")
    @ApiOperation("获取所有组织")
    public R allOrganization(){
        return R.ok();

    }

    //个人中心模块
    @PostMapping("/personCenterMessage")
    @ApiOperation("个人中心个人信息页面")
    public R personCenterMessagePage(@RequestHeader("token") String token){
        Claims claims = JwtUtils.parseJWT(token);
        String id_string = claims.getSubject();
        Integer id = Integer.parseInt(id_string);
        User user = userService.getUserByUserId(id);
        List<Role> roleList = userRoleService.getRoleByUserId(id);
        return R.ok().put("user",user).put("roleList",roleList);
    }


    //个人中心模块
    @GetMapping("/getUserBriefInfo")
    @ApiOperation("获取用户简要信息(不含隐私信息)")
    public R getUserBriefInfo(@NotBlank @RequestParam(value = "userId")  Integer userId){
        User user = userService.getUserBriefInfoByUserId(userId);
        return R.ok().put("user",user);
    }

    @PostMapping("/personUpdateUser")
    @ApiOperation("修改个人信息")
    public R personUpdateUser(@RequestHeader("token") String token,@Valid @RequestBody UniAppPersonUpdateUserReq req){
            //手机验证码跟redis比对
        if (!req.getVerifyCode().equals(redisUtil.get(req.getPhone()))) {
            return R.error("手机验证码不正确或超时！");
        }else if (!Pattern.matches(pattern, req.getName())){
            return R.error("名字不符合规范，需全部为中文且2~10字之间");
        }else {
            //String token = request.getHeader("token");
            Claims claims = JwtUtils.parseJWT(token);
            String id_string = claims.getSubject();
            Integer id = Integer.parseInt(id_string);

            User user = new User();
            user.setPhoto(req.getPhoto());
            user.setTelephone(req.getPhone());
            //status为2时是游客状态
            user.setStatus(StatusEnum.VISITOR.getCode());
            user.setId(id);
            user.setEmail(req.getEmail());
            user.setName(req.getName());
            user.setSex(req.getSex());

            userService.editPersonMessage(user);

            return R.ok("修改成功");
        }
    }

    @PostMapping("/sendSms")
    @ApiOperation("发送短信验证码")
    public R sendMsg(@NotNull @RequestParam String phone) {
        if (!CommonUtils.isPhone(phone)) {
           return R.error("手机号码输入不正确");
        }else {
            String errMsg = smsService.sendMsg(phone);
            if(StringUtil.isEmpty(errMsg)){
                return R.error("短信发送："+errMsg);
            }else {
                return R.ok("短信发送成功");
            }
        }
    }



    //显示所有组织
    @PostMapping("/showAllCommunist")
    @ApiOperation("显示所有组织")
    public R showMyCommunist(@RequestParam @ApiParam("组织名字") String organizationName){
            //还未加入组织，显示所有组织
            List<OrganizationDTO> organizationDTOList= organizationService.getAllCommunist(organizationName);
            return R.ok().put("organizationDTOList",organizationDTOList);
    }




    //显示我的组织
    @PostMapping("/showMyCommunist")
    @ApiOperation("显示我的组织")
    public R showAllCommunist(@RequestHeader("token") String token){
        Claims claims = JwtUtils.parseJWT(token);
        String id_string = claims.getSubject();
        Integer userId = Integer.parseInt(id_string);



        String organizationName = userOrganizationService.selectOrganizationNameByUserId(userId);
        if (StringUtil.isEmpty(organizationName)){
            return R.ok("未加入组织");
        }

        User user = userService.getUserByUserId(userId);
        if(Objects.equals(user.getStatus(), StatusEnum.AUDIT.getCode())){
            return R.error("您的申请还在审核中，请耐心等待");
        }

        //返回组织的所有信息
        Organization organization =organizationService.getOrganizationByOrganizationName(organizationName);
        if(organization == null){
            throw new GlobalException("查询组织失败，该组织不存在");
        }
        return R.ok("查询成功").put("organization",organization);

    }

    //显示某个组织
    @GetMapping("/showCommunist")
    @ApiOperation("显示某个组织")
    public R showCommunist(@RequestParam @NotBlank @ApiParam("组织id") Integer id){
        //返回组织的所有信息
        Organization organization =organizationService.getOrganizationByOrganizationId(id);
        if(organization == null){
            throw new GlobalException("查询组织失败，该组织不存在");
        }
        return R.ok("查询成功").put("organization",organization);

    }

//    //模糊查找搜索组织
//    @PostMapping("/findOrganizationName")
//    @ApiOperation("模糊查找组织")
//    public R findOrganizationName(@RequestParam @NotBlank @ApiParam("组织名字") String organizationName){
//        List<OrganizationDTO> organizationDTOList = organizationService.findOrganizationName(organizationName);
//        if (organizationDTOList == null && organizationDTOList.size() ==0) {
//            return R.error("查询失败，没有该组织名字");
//        }
//        return R.ok("模糊查找成功").put("organizationDTOList",organizationDTOList);
//    }

    //游客变成普通党员的过程
    @PostMapping("/joinCommunist")
    @ApiOperation("加入组织")
    @Transactional
    public R joinCommunist(@RequestHeader("token") String token,
                           @RequestParam @NotBlank @ApiParam("组织ID") Integer organizationId){
        Claims claims = JwtUtils.parseJWT(token);
        String id_string = claims.getSubject();
        Integer id = Integer.parseInt(id_string);
        User user = new User();
        user.setId(id);
        user.setStatus(StatusEnum.AUDIT.getCode());
        userService.editPersonMessage(user);
        Integer user_organization_id = userOrganizationService.joinCommunistByOrganizationIdAndUserId(organizationId, id);
        if (user_organization_id != null) {
            return R.ok("提交成功");
        }else {
            return R.error("提交失败");
        }

    }



    private void saveCacheToken(String token,int userId){
        //cacheExpire 为1 设置token存储一天时间，跟web端同步的token设置时间
        redisTemplate.opsForValue().set(token,userId+"",cacheExpire, TimeUnit.DAYS);
    }
}
